package solver.moves;

import java.util.Collections;
import java.util.List;

import model.MachineSelector;
import model.SolverEnvironment;

public class RuinAndReconstructMove extends AbstractComplexMove {

	//Allow up to 10% worst cost
	private static double RUINRATE = 1.01;

	MachineSelector ms;
	
	public RuinAndReconstructMove(SolverEnvironment env, MachineSelector ms) {
		super(env);
		this.ms = ms;
	}


	@Override
	public boolean performMove() {
		boolean success = false;
		long init_cost=getCc().getNewSolutionCost();
		
		for(int i=1;i<20;i++){
			int orig_m1_index = ms.getMostLoadedMachine(i);
			List<Integer> l1 = getCurrent_solution().getProcessesForMachine(orig_m1_index);
			if (l1.size()==0)
				return false;
			Collections.shuffle(l1,getRandom());
			for(Integer p:l1){
				long local_cost=getCc().getNewSolutionCost(); 
				if (testSequentiallyBest(p, orig_m1_index, orig_m1_index+getProblem().M-1)){
					long new_cost=getCc().getPotentialSolutionCost();
					if(new_cost>RUINRATE*init_cost)
						getInvoker().undoLastCommand();
					else{
						getCc().updateNewSolutionCost();
						success=true;
					}
				}
			}
		}
//		invoker.clearCommands();
		return success;
	}


}
